import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import moment from 'moment';
import { Input, Select, Checkbox,Radio,Modal, Form, Button, message, Spin,Row, Col, Table, InputNumber } from 'antd';

const FormItem = Form.Item;
const { Option } = Select;

export default class Index extends Component{
  
  state={
    selectedIds:[],
    deliverWay:1,
    listNum:[],
    selectedListNum:[],
    foot:{footer:null}    
  }

  componentWillMount() {
    window.Isoption = false;
  }

  componentDidMount(){
    window.Isoption = true;
    const {list,addressListLoading, expressListLoading} = this.props;
    const { listNum } = this.state;
    let arr=[];
    list.OrderItem&&list.OrderItem.forEach(item=>{
      if(item.RightsStatus!=5){
        if(item.BuyNum-item.AlreadySend>0){
          arr.push(item.Id);
          listNum.push(item.BuyNum-item.AlreadySend);
        }else{
          listNum.push(0);
        }       
      }            
    })
    this.setState({
      selectedIds:arr,
      listNum,
      selectedListNum:[...listNum],      
    })   
  }

	okHandle = () => {
    const {form,comfirm,list} = this.props;
    const { selectedIds ,listNum,selectedListNum} = this.state;
    if(!selectedIds.length) return message.error('未选择发货商品');
    form.validateFields((err, values) =>{     
      if(values.deliverWay==1&&(!values.storeAddressId||!values.expressId||!values.waybillNumber)) return;
      let params={
        orderId:list.Id,
        orderNo:list.OrderNo,
        storeAddressId:values.storeAddressId,
        expressId:values.deliverWay==1?values.expressId:0,
        waybillNumber:values.waybillNumber,
        listItemId:selectedIds,
        listNum:selectedListNum.filter(v=>v>0),       
      };      
      if(typeof comfirm === 'function') comfirm(params);
    });
  }  
  

  handleModalVisible = () => {
    const { handleModalVisible } =this.props;
    if(typeof handleModalVisible === 'function') handleModalVisible();
  }

  changeDeliverWay = (e) =>{
    this.setState({
      deliverWay:e.target.value
    })
  }

  changeDeliverNum = (e,record,index) => {
    const { listNum,selectedListNum} = this.state;    
    listNum[index]=e;
    selectedListNum[index]=e;
    this.setState({
      listNum,
      selectedListNum
    })
  }

	render(){
    const {modalVisible,form:{getFieldDecorator},addressList,expressList,list,confirmLoading,addressListLoading,expressListLoading,allLoading} = this.props;
    const {selectedIds,deliverWay,listNum,foot} = this.state;
    const columns = [
      {
        title: '商品',
        dataIndex: 'ProductName', 
        width:'40%',
        render:(val,record)=>(          
          <div className="xkd-inline-block xkd-width-per-100 xkd-vertical-align-top">
            <div style={{lineHeight:'20px'}}>{record.ProductName}</div>
            <div style={{lineHeight:'20px'}}>{record.SkuName}</div>
           </div>
        )      
      },
      {
        title: '购买数量',
        dataIndex: 'BuyNum',
        align: 'right',
        width: '20%',
      },
      {
        title: '已发',
        dataIndex: 'AlreadySend',
        align: 'right',
        width: '20%',          
      },
      {
        title: '本次发',
        dataIndex: 'DeliverNum',
        width: '20%',   
        render:(text,record,index) =>{                   
          if(record.BuyNum-record.AlreadySend<=0){
            return <InputNumber value={0}  disabled={true} />
          }else{           
            return (              
              <InputNumber value={listNum[index]}  onChange={(e)=>this.changeDeliverNum(e,record,index)} min={1} max={record.BuyNum-record.AlreadySend}/>
            )  
          }          
      }

      },
    ];

    const rowSelection = {
      selectedRowKeys: selectedIds,
      onChange: (selectedIds, selectedRows) => {
        const {listNum,selectedListNum} = this.state;
        const { list } = this.props;       
        let arr=[];
        selectedIds.forEach((v)=>{
          let index= list.OrderItem.findIndex(item=>item.Id==v);          
          arr.push(listNum[index])
        })
        this.setState({
          selectedIds: selectedIds,
          selectedListNum:arr,
        });
      },
      getCheckboxProps: record => ({
        disabled: record.BuyNum-record.AlreadySend<=0, // Column configuration not to be checked
        // name: record.name,
      }),
    };
    let obj=addressListLoading||expressListLoading?foot:{}
		 return (		
      <Modal
        destroyOnClose
        centered
        title="订单发货"
        visible={modalVisible}
        onOk={this.okHandle}        
        confirmLoading={ confirmLoading }
        onCancel={this.handleModalVisible}
        width={640}  
        {...obj}
        className={`${styles.deliverModal}`}               
      >      
          <Spin spinning={addressListLoading||expressListLoading}>
            <Table
                //loading={loading}
                //bordered
                scroll={{ y: list.OrderItem.length>2?146:0 }}              
                rowKey={record => record.Id}
                dataSource={list.OrderItem}
                columns={columns}
                rowSelection={rowSelection}
                // onChange={this.handleStandardTableChange}
                 pagination={false}
            />  
            <div className="xkd-mt16" id="deliverModal" >
            <Row>
              <FormItem 
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 17 }} 
                label="收货人信息" 
                style={{marginBottom:16}}            
              >
                <div style={{paddingTop:10,lineHeight:'22px'}}>
                  <div>{list.ReceivingName}，{list.ReceivingTelephone}</div>
                  <div>{list.receivingAddress}</div>
                </div>
              </FormItem>
            </Row>
            <Row className={styles.deliverWay}>
              <FormItem 
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 16 }} 
                label="发货方式"                
              >
                {getFieldDecorator('deliverWay',{
                  initialValue:1
                })(
                  <Radio.Group  style={{width:'100%'}} onChange={this.changeDeliverWay} >
                      <Row>
                          <Col span={6}>
                              <Form.Item style={{marginBottom:0}}>
                                <Radio value={1}>需要物流</Radio>
                              </Form.Item>
                          </Col>
                          <Col span={6} >
                              <Form.Item style={{marginBottom:0}}>
                                <Radio value={2}>无需物流</Radio>
                              </Form.Item>
                          </Col>  
                      </Row>                                                                                                                                            
                  </Radio.Group>
                )}
              </FormItem>
            </Row>
            {deliverWay==1?
              <Fragment>
            <Row>
              <FormItem 
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 10 }} 
                label="物流公司"
              >
                {getFieldDecorator('expressId',{
                  rules: [{ required: true, message:'此项为必选项' }],
                  validateTrigger:'onBlur'
                })(
                    <Select style={{ width: '100%' }}>
                    {expressList &&
                  
                  expressList.map(item => {
                        return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                      })}
                  </Select>
                )}
              </FormItem>
            </Row>
            <Row>
              <FormItem 
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 10 }} 
                label="快递单号"
              >
                {getFieldDecorator('waybillNumber', {
                  rules: [{ required: true, message:'此项为必选项' }],
                  validateTrigger:'onBlur'
                })(
                    <Input style={{ width: '100%' }}/>
                )}
              </FormItem>
            </Row>
            <Row>
              <FormItem 
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 10 }} 
                label="发货地址"
              >
                {getFieldDecorator('storeAddressId', {
                  initialValue:list.DefaultAddressId||undefined,
                  rules: [{ required: true, message:'此项为必选项' }],
                  validateTrigger:'onBlur'
                })(
                    <Select style={{ width: '100%' }} getPopupContainer={()=>document.querySelector("#deliverModal")}>
                    {addressList &&
                  
                      addressList.map(item => {
                        return <Option value={item.Id} key={item.Id}>{item.Name}</Option>;
                      })}
                  </Select>
                )}
              </FormItem>
            </Row>
            </Fragment>:null
            }
            </div>
          </Spin>
      </Modal>
    );
	}
}